import { defineStore } from 'pinia'
import { $utils } from '@/utils'
import updateImg from '@/assets/img/updata.png'
import { useGameStore } from './game'
import {
  cancelOrder,
  cancelBatchOrder as cancelBatchOrderApi,
  findOrderPage as findOrderPageApi,
  findRepetitionBet as findRepetitionBetApi,
} from '@/api'
import { showToast } from 'vant'
import { intersection } from 'lodash-es'

let saveLastOption = []

export const useInvestStore = defineStore('invest', {
  state: () => ({
    showEditMoneyPopup: false, //显示弹窗
    showInvestPopup: false, // 显示投入金额弹窗
    investMoneyIndex: 1, //投注金额索引
    investList: [], //下注内容
    showCancelOrderPopup: false, // 显示可撤单的弹窗
    lastInvestList: [], //最近一期投注记录
    historyData: {
      records: [],
    }, //投注记录
    inputMoney: '10', //自定义金额
    openConfirmCancelOrder: false, // 确认撤销全部订单弹窗
    investMoneyOpts: [
      { money: '0', img: updateImg },
      { money: '10' },
      { money: '20' },
      { money: '30' },
      { money: '50' },
      { money: '100' },
    ],
    gameStore: useGameStore(),
    rulesShow: false, //显示游戏规则
    index: 0,
  }),
  getters: {
    // 获得编辑金钱选项
    getEditInvestMoneyOpts() {
      const list = JSON.parse(JSON.stringify(this.investMoneyOpts.slice(1)))
      return list
    },

    // 下注数量
    getInvestCount() {
      if ($utils.isEmpty(this.investList)) return 0
      return this.investList.length
    },

    // 投注总额
    getInvestMoney() {
      let money = 0
      if ($utils.isEmpty(this.investList)) return money
      this.investList.forEach((item) => {
        money += Number(item.betAmount)
      })
      return money
    },

    // 获得单注总额
    getSingleInvestMoney() {
      // return state.inputMoney ? state.inputMoney : state.investMoneyOpts[state.investMoneyIndex].money;
      return this.inputMoney
    },

    // 多少钱
    howMuch() {
      return `已选${this.getInvestCount}注，${this.getInvestMoney}元`
    },

    getLastInvestList() {
      return this.lastInvestList
    },

    // 下注按钮文字
    getInvestBtnText() {
      if (!$utils.isEmpty(this.investList)) return { canBat: true, text: '立即下注' }
      if ($utils.isEmpty(this.lastInvestList)) return { canBat: true, text: '立即下注' }
      const currentSonGameTag = this.gameStore.currentSonGameTag
      const sonTypeList = this.lastInvestList.map((item) => item.playTypeCode)
      if (Array.isArray(currentSonGameTag)) {
        if (intersection(sonTypeList, currentSonGameTag).length >= 1) return { canBat: false, text: '重复下注' }
      }
      if (sonTypeList.indexOf(currentSonGameTag) === -1) return { canBat: true, text: '立即下注' }
      return { canBat: false, text: '重复下注' }
    },
  },

  actions: {
    // 设置自定义金额
    setInputMoney(val) {
      this.inputMoney = val
      this.calculatedAmount()
    },
    // 显示游戏规则
    setRules(val) {
      this.rulesShow = val
    },
    // 更新下注内容
    setInvestNum(list) {
      this.investList = list
    },

    // // 删除一个下注内容
    deleteAnInvest(index) {
      this.investList.splice(index, 1)
    },

    // 显示投注金额弹窗
    showPopup(isShow) {
      this.showEditMoneyPopup = isShow
      if (isShow) this.saveLastOpts()
    },
    // 显示投注金额弹窗
    showRulesPopup(isShow, i?: number) {
      this.rulesShow = isShow
      this.index = i ?? 0
      // if (isShow) this.saveLastOpts()
    },
    // 计算价格，每一次改价都要给每个子项赋值
    calculatedAmount() {
      const money = this.inputMoney

      const list = []
      this.investList.map((item) => {
        item.betAmount = money
        list.push(item)
      })
      this.investList = list
    },

    // 选择投注金额
    setInvestMoney(i) {
      this.investMoneyIndex = i
      this.inputMoney = this.investMoneyOpts[this.investMoneyIndex].money
      // 0是编辑
      if (i === 0) {
        this.showPopup(true)
      } else {
        this.calculatedAmount()
      }
    },

    // 保存最后一次编辑选项
    saveLastOpts() {
      saveLastOption = JSON.parse(JSON.stringify(this.investMoneyOpts))
    },

    // 恢复选项
    recoveryOption() {
      this.investMoneyOpts = saveLastOption
    },

    // 修改金额
    editMoney(e) {
      const index = e.index + 1
      this.investMoneyOpts[index].money = e.item.money
    },

    // 保存选项
    saveMoneyOpts() {
      this.showPopup(false)
    },

    //重置金额
    initInvestMoney() {
      this.investMoneyOpts = [
        { money: '0', img: updateImg },
        { money: '10' },
        { money: '20' },
        { money: '30' },
        { money: '50' },
        { money: '100' },
      ]
    },

    // 投注成功了追加内容
    setHistoryData() {
      // this.historyData.records = [...list, ...this.historyData.records];
    },

    // 控制确认投注窗口
    openOrderPopup(isOpen) {
      this.showOrderPopup = isOpen
    },

    // 可撤单弹窗
    openCancelOrderPopup(isOpen) {
      this.showCancelOrderPopup = isOpen
      if (isOpen) this.findOrderPage()
    },

    // 取消一个注单
    async cancelAnOrder(e) {
      const gameType = this.gameStore.currentGame
      const params = {
        id: e.item.id,
        lotteryCode: gameType,
      }
      const res = await cancelOrder(params)
      // if (res.code != 200) {
      //   return
      // }
      showToast(res.message)
      this.historyData.records.splice(e.index, 1)
    },

    // 批量取消订单
    async cancelBatchOrder(refMessageId) {
      const gameType = this.gameStore.currentGame
      const ids = this.historyData.records?.map?.((item) => item.id) ?? []
      const params: any = {
        id: ids,
        lotteryCode: gameType,
      }
      if (refMessageId) params.refMessageId = refMessageId
      const res = await cancelBatchOrderApi(params)
      if (res.code !== 200) {
        return
      }
      this.openConfirmCancelOrder = false
      this.showCancelOrderPopup = false
      showToast(res.message ?? '撤单成功')
      this.historyData.records = []
    },

    //确认撤销全部订单弹窗
    setOpenConfirmCancelOrder(isOpen) {
      this.openConfirmCancelOrder = isOpen
    },

    //点击遮罩层时触发
    closeOverlay() {
      this.recoveryOption()
      this.showPopup(true)
    },

    // 更改金额
    changeAnAmount(e) {
      this.investList[e.index] = e.item
    },

    // setLastInvestList(list) {
    //   this.lastInvestList = list
    // },
    setLastInvestList(value) {
      this.lastInvestList = value
    },

    // 获取历史订单
    async findOrderPage() {
      if (!this.gameStore?.latestGameData?.value?.periodsNumber) return
      // 开奖前10分钟可以撤单
      const params = {
        current: 1,
        size: 100,
        orderStatus: 0,
        periodsNumber: this.gameStore.latestGameData.value.periodsNumber, //按期号获取， 期号和开始时间，结束时间，必须传一个
        lotteryCode: this.gameStore.currentGame,
      }
      const res = await findOrderPageApi(params)
      res.data.records = res?.data?.records ?? []
      this.historyData = res.data
    },
    //获取最近投注记录
    async findRepetitionBet() {
      const params = {
        lotteryCode: this.gameStore.currentGame,
      }
      const res = await findRepetitionBetApi(params)
      this.lastInvestList = res.data ?? []
    },
  },
})
